<template>
    <div class="details-body">
        <el-row>
            <h1 style="margin: 0 auto;">{{ articleData.title }}</h1>
        </el-row>
        <el-row>
            <v-md-editor :model-value="articleData.content" mode="preview"></v-md-editor>
        </el-row>
        <br>
        <el-row v-if="config.articleExist" style="margin-bottom: 40px;">
            <el-text size="large">分类:</el-text>
            <el-link type="success" style="margin-right: 30px;margin-left: 5px;"
                     @click="clickClassification(articleData.classification.id)">
                <el-text type="success" size="large">{{ articleData.classification.classificationName }}</el-text>
            </el-link>
            <div v-if="articleData.prevArticleId!=null" style="margin-left: 20px;margin-right: 20px">
                上一篇:
                <el-link type="primary" @click="router.push(`/article-details/${articleData.prevArticleId}`)">
                    {{ articleData.prevArticleTitle }}
                </el-link>
            </div>
            <div v-if="articleData.nextArticleId!=null" style="margin-right: 20px">
                下一篇:
                <el-link type="primary" @click="router.push(`/article-details/${articleData.nextArticleId}`)">
                    {{ articleData.nextArticleTitle }}
                </el-link>
            </div>
            <el-tag style="margin-right: 10px;" type="primary" v-for='tag in articleData.articleTags'
                    @click="clickTag(tag.id)">{{ tag.tagName }}
            </el-tag>
        </el-row>
        <el-row v-if="config.articleExist">
            <el-col :span="8">
                <el-avatar shape="square" class="publish-user-avatar" size="large" src="squareUrl"/>
                <el-text class="publish-user-name" truncated size="large">{{
                        publisherUserInfo.publishUserNickName
                    }}
                </el-text>

                <el-text class="publish-user-info">{{ publishUserFollowerAndContentInfo }}</el-text>
                <el-text class="publish-user-info" style="margin-left: 20px;">{{
                        "等级:" +
                        publisherUserInfo.publishUserLevel
                    }}
                </el-text>
                <el-button v-if="!publisherUserInfo.followThisUser" type="success" @click="followUser(true)" round
                           class="follow-button">关注
                </el-button>
                <el-button v-else type="info" round @click="config.cancelFollowUserDialogVisible = true"
                           class="follow-button">取消关注
                </el-button>
            </el-col>
            <el-col :span="8">
                <el-button v-if="!articleData.currentUserLike" type="success"
                           style="margin-left: 20%; margin-right: 5px;"
                           size="large" :icon="Check" @click="clickLike(true)" circle/>
                <el-button v-else type="info" @click="clickLike(false)" style="margin-left: 20%; margin-right: 5px;"
                           size="large" :icon="Check" circle/>
                <el-text size="large">{{ articleData.likeNumber + "点赞" }}</el-text>
                <el-button v-if="!articleData.currentUserCollect" type="warning"
                           style="margin-left: 20px; margin-right: 5px;"
                           size="large" :icon="Star" @click="clickCollect" circle/>
                <el-button v-else type="info" @click="clickCollect" style="margin-left: 20px; margin-right: 5px;"
                           size="large" :icon="Star" circle/>
                <el-text size="large">{{ articleData.collectNumber + "收藏" }}</el-text>
                <el-button v-if="articleData.currentUserFeedRiceGrainsNumber < 10" type="primary"
                           style="margin-left: 20px; margin-right: 5px;" size="large" :icon="Food" circle
                           @click="clickFeedArticle"/>
                <el-button v-else type="info" disabled style="margin-left: 20px; margin-right: 5px;" size="large"
                           :icon="Food"
                           circle/>
                <el-text size="large">{{ articleData.riceGrainsNumber + "米粒" }}</el-text>
            </el-col>
            <el-col :span="8">
                <el-text type="info" class="publish-date-time">发布于{{ articleData.publishDateTime }}</el-text>
            </el-col>
        </el-row>
        <Comment :articleId="articleData.id" v-if="config.loadingCompleted"></Comment>
        <br/><br/><br/><br/>

        <!-- 收藏弹框 -->
        <el-dialog v-model="config.collectDialogVisible" title="收藏文章" width="25%" center>
            <div style="max-height: 20vh;overflow-y: scroll">
                <el-row class="collect-box" v-for="item in collectGroup">
                    <el-col :span="18">
                        <el-checkbox :label="item.collectGroupName" v-model="item.articleInCollectGroup" size="large"
                                     style="font-size: larger"/>
                    </el-col>
                    <el-col :span="6">
                        <el-text>{{ "已收藏" + item.collectContentCount }}</el-text>
                    </el-col>
                </el-row>
            </div>

            <el-row style="margin-left: 20%;margin-top: 30px">
                <el-input style="width: 50%;margin-right: 20px" v-model="config.addCollectGroupName"/>
                <el-button type="success" @click="addCollectGroup">新增</el-button>
            </el-row>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="config.collectDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="collectArticle">
                    收藏
                </el-button>
            </span>
            </template>
        </el-dialog>


        <!-- 投喂弹框 -->
        <el-dialog v-model="config.feedDialogVisible" title="投喂作者米粒" width="30%" center>
        <span style="margin-left: 20%;">
            投喂数量:&nbsp;
            <el-input-number precision="0" v-model="config.feedRiceGrainsNumber" min="1" max="10" class="mx-4"/>
            <el-button type="success" style="margin-left: 20px;" @click="clickMaxFeedRiceGrains">最多</el-button>
        </span>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="config.feedDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="feedPublisher">
                    投喂
                </el-button>
            </span>
            </template>
        </el-dialog>


        <!-- 取关弹框 -->
        <el-dialog v-model="config.cancelFollowUserDialogVisible" title="提示" width="30%" center>
        <span>
            挖,你真的要取消关注我吗? ≧ ﹏ ≦
        </span>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="config.cancelFollowUserDialogVisible = false">取消</el-button>
                <el-button type="danger" @click="followUser(false)">
                    确认取消关注
                </el-button>
            </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {useRouter} from 'vue-router'
import {reactive, onMounted, watch, computed, nextTick, getCurrentInstance} from 'vue'
import Comment from '../../components/common/Comment.vue'


import InfoUtil from '../../utils/InfoUtil.js'
import RequestUtil from '../../utils/RequestUtil.js'

import {Check, Star, Food} from '@element-plus/icons-vue'
import StringUtil from "@/utils/StringUtil";


export default {
    setup() {
        const router = useRouter();

        const config = reactive({
            //查询的文章是否存在
            articleExist: false,
            //投喂框是否展示
            feedDialogVisible: false,
            //取关提示框
            cancelFollowUserDialogVisible: false,
            //收藏框
            collectDialogVisible: false,
            //投喂米粒数量
            feedRiceGrainsNumber: 0,
            //当前组件是否加载完成
            loadingCompleted: false,
            //新增的组名称
            addCollectGroupName: ""
        })

        const publisherUserInfo = reactive({
            publishUserId: 0,//发布文章的用户id
            avatarResourceName: "",//发布文章的用头像图片路径
            publishUserNickName: "",//发布文章的用户昵称
            contentNumber: 0,//发布文章的用户内容总数
            followingNumber: 0,//发布文章的用户粉丝数
            publishUserLevel: 0,//发布文章的用户用户等级
            followThisUser: false //当前用户是否关注了该用户
        })

        const articleData = reactive({
            id: 0,
            title: "",//标题
            content: "",//正文
            likeNumber: 0,//喜欢数
            collectNumber: 0,//收藏数
            riceGrainsNumber: 0,//米粒数
            viewNumber: 0,//观看数
            publishDateTime: "",//发布日期
            articleTags: [],//标签
            classification: {//所属分类
                id: 0,
                classificationName: ""
            },
            currentUserLike: false, //当前用户是否喜欢了这篇文章
            currentUserCollect: false, //当前用户是否收藏了这篇文章
            currentUserFeedRiceGrainsNumber: 0, //当前用投喂了这篇文章多少米粒
            nextArticleTitle: "",
            nextArticleId: 0,
            prevArticleTitle: "",
            prevArticleId: 0
        })

        let collectGroup = reactive([]);


        //初始化文章信息
        const initArticleDetail = () => {
            const articleId = router.currentRoute.value.params.articleId
            RequestUtil.sendGetRequest("/article/getArticleInfo", {"articleId": articleId}).then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message);
                        return;
                    }
                    config.loadingCompleted = false;
                    config.articleExist = true;
                    const responseData = res.data;
                    //获取文章和发布者信息
                    const articleVO = responseData.articleVO;
                    const publishUserVO = responseData.publishUserVO;
                    //填充文章信息
                    articleData.title = articleVO.title;
                    articleData.id = articleVO.id;
                    articleData.content = articleVO.content;
                    articleData.likeNumber = articleVO.likeNumber;
                    articleData.viewNumber = articleVO.viewNumber;
                    articleData.collectNumber = articleVO.collectNumber;
                    articleData.riceGrainsNumber = articleVO.riceGrainsNumber;
                    articleData.publishDateTime = articleVO.publishDateTime;
                    articleData.articleTags.splice(0, articleData.articleTags.length);
                    for (let i = 0; i < articleVO.tags.length; i++) {
                        articleData.articleTags.push(articleVO.tags[i])
                    }
                    articleData.classification.id = articleVO.articleClassification.id;
                    articleData.classification.classificationName = articleVO.articleClassification.classificationName;
                    articleData.currentUserFeedRiceGrainsNumber = articleVO.currentUserFeedRiceGrainsNumber;
                    articleData.currentUserLike = articleVO.currentUserLike;
                    articleData.currentUserCollect = articleVO.currentUserCollect;
                    articleData.nextArticleId = articleVO.nextArticleId;
                    articleData.nextArticleTitle = articleVO.nextArticleTitle;
                    articleData.prevArticleId = articleVO.prevArticleId;
                    articleData.prevArticleTitle = articleVO.prevArticleTitle;
                    //填充用户信息
                    publisherUserInfo.publishUserId = publishUserVO.publishUserId;
                    publisherUserInfo.avatarResourceName = publishUserVO.avatarResourceName;
                    publisherUserInfo.publishUserNickName = publishUserVO.publishUserNickName;
                    publisherUserInfo.contentNumber = publishUserVO.contentNumber;
                    publisherUserInfo.followingNumber = publishUserVO.followingNumber;
                    publisherUserInfo.publishUserLevel = publishUserVO.publishUserLevel;
                    publisherUserInfo.followThisUser = publishUserVO.followThisUser;
                    //去加载评论组件
                    setTimeout(() => {
                        config.loadingCompleted = true;
                    }, 0)
                },
                (err) => {

                    InfoUtil.error("发送请求失败");
                }
            )
        }


        watch(() => router.currentRoute.value.path,
            (toPath) => {
                if (toPath.indexOf("/article-details") == 0) {
                    initArticleDetail();
                }
            }, {immediate: true, deep: true}
        )
        const publishUserFollowerAndContentInfo = computed(() => {
            return "粉丝:" + publisherUserInfo.followingNumber + " 内容: " + publisherUserInfo.contentNumber;
        })

        //点击分类
        const clickClassification = (classificationId) => {
            alert(classificationId)
        }

        //点击标签
        const clickTag = (tagId) => {
            alert(tagId)
        }
        //点赞 operation代表点赞或取消点赞
        const clickLike = (operation) => {
            let reuqestPath = "/userArticleLike/cancelLikeArticle";
            if (operation) {
                reuqestPath = "/userArticleLike/likeArticle"
            }
            RequestUtil.sendGetRequest(reuqestPath, {"articleId": articleData.id}).then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message);
                        return
                    }
                    //点赞
                    if (operation) {
                        articleData.likeNumber++;
                        articleData.currentUserLike = true;
                    } else {
                        articleData.currentUserLike = false;
                        articleData.likeNumber--;
                    }
                    InfoUtil.success(res.message);
                },
                (err) => {
                    InfoUtil.error("发送请求失败");
                }
            )
        }
        //点击展示投喂按钮
        const clickFeedArticle = () => {
            config.feedDialogVisible = true;
        }
        //点击最多投喂按钮
        const clickMaxFeedRiceGrains = () => {
            config.feedRiceGrainsNumber = 10 - articleData.currentUserFeedRiceGrainsNumber;
        }

        //点击投喂按钮
        const feedPublisher = () => {
            const requestData = {
                "articleId": articleData.id,
                "riceGrainsNumber": config.feedRiceGrainsNumber
            }
            RequestUtil.sendGetRequest("/userArticleRiceGrains/feedArticlePublisher", requestData).then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message);
                        return
                    }
                    //设置当前用户投喂数量
                    articleData.currentUserFeedRiceGrainsNumber =
                        articleData.currentUserFeedRiceGrainsNumber + config.feedRiceGrainsNumber;
                    //关闭投喂框
                    config.feedDialogVisible = false;
                    //设置文章收到的投喂数量
                    articleData.riceGrainsNumber = articleData.riceGrainsNumber + config.feedRiceGrainsNumber;
                    InfoUtil.success(res.message);
                },
                (err) => {
                    InfoUtil.error("发送请求失败");
                }
            )
        }

        //点击收藏按钮
        const clickCollect = () => {
            collectGroup.splice(0, collectGroup.length)
            RequestUtil.sendGetRequest("/userCollectGroup/list", {"articleId": articleData.id}).then(
                (res) => {
                    if (res.code === 666) {
                        //没有分组的情况.忽略
                        return;
                    }
                    if (res.code !== 200) {
                        InfoUtil.warning(res.message);
                        return
                    }
                    for (let i = 0; i < res.data.length; i++) {
                        collectGroup.push(res.data[i])
                    }
                },
                (err) => {
                    InfoUtil.error("获取收藏分组请求失败")
                }
            )
            config.collectDialogVisible = true;
        }

        //点击新增分组
        const addCollectGroup = () => {
            if (StringUtil.isEmpty(config.addCollectGroupName)) {
                InfoUtil.warning("组名不能为空");
                return
            }
            if (config.addCollectGroupName.length > 20) {
                InfoUtil.warning("分组名称超出最大长度");
                return;
            }
            const requestData = {
                "groupName": config.addCollectGroupName,
                "serialNumber": 0,
                "groupIsOvert": false
            }
            RequestUtil.sendPostRequest("/userCollectGroup/save", requestData).then(
                (res) => {
                    if (res.code !== 200) {
                        InfoUtil.warning(res.message);
                        return
                    }
                    const groupId = res.data;
                    collectGroup.push({
                        "collectGroupName": config.addCollectGroupName,
                        "articleInCollectGroup": false,
                        "collectContentCount": 0,
                        "collectGroupId": groupId
                    })
                    InfoUtil.success(res.message)
                    config.addCollectGroupName = "";

                }
            )

        }

        //点击收藏按钮
        const collectArticle = () => {
            const requestData = [];
            for (let collectGroupElement of collectGroup) {
                if (!collectGroupElement.articleInCollectGroup) {
                    continue;
                }
                const item = {
                    articleId: articleData.id,
                    groupId: collectGroupElement.collectGroupId
                }
                requestData.push(item);
            }
            //认为取消该文章的所有收藏
            if (requestData.length === 0) {
                RequestUtil.sendGetRequest("/userArticleCollect/removeAllCollect", {"articleId": articleData.id}).then(
                    (res) => {
                        if (res.code !== 200) {
                            InfoUtil.warning(res.message)
                            return
                        }
                        InfoUtil.success(res.message)
                        articleData.currentUserCollect = false;
                        config.collectDialogVisible = false;
                    },
                    (err) => {
                        InfoUtil.error("发送请求失败");
                    }
                )
                return
            }

            RequestUtil.sendPostRequest("/userArticleCollect/update", requestData).then(
                (res) => {
                    if (res.code !== 200) {
                        InfoUtil.warning(res.message)
                        return
                    }
                    InfoUtil.success(res.message)
                    articleData.currentUserCollect = true;
                    config.collectDialogVisible = false;
                },
                (err) => {
                    InfoUtil.error("发送请求失败");
                }
            )

        }


        //关注/取关按钮
        const followUser = (operation) => {
            let requestPath = "/userRelation/cancelFollowUser";
            if (operation) {
                requestPath = "/userRelation/followUser"
            }
            RequestUtil.sendGetRequest(requestPath, {"followUserId": publisherUserInfo.publishUserId}).then(
                (res) => {
                    if (res.code != 200) {
                        InfoUtil.warning(res.message);
                        return
                    }
                    //关注
                    if (operation) {
                        publisherUserInfo.followingNumber++;
                        publisherUserInfo.followThisUser = true;
                    } else {
                        publisherUserInfo.followingNumber--;
                        publisherUserInfo.followThisUser = false;
                        //关闭确认取消关注弹框
                        config.cancelFollowUserDialogVisible = false;
                    }
                    InfoUtil.success(res.message);
                },
                (err) => {
                    InfoUtil.error("发送请求失败");
                }
            )

        }


        return {
            Check, Star, Food, router,
            publisherUserInfo, articleData, config, publishUserFollowerAndContentInfo, collectGroup,
            clickClassification, clickTag, clickLike, clickFeedArticle, clickMaxFeedRiceGrains,
            feedPublisher, clickCollect, followUser, addCollectGroup, collectArticle
        }
    },

    components: {Comment}

}

</script>

<style scoped>
.details-body {
    background-color: #fff;
    padding-left: 20px;
    padding-right: 20px;
}

.collect-box {
    align-items: center;
}


.publish-user-name {

    width: 200px;
    float: left;
    position: relative;
    top: 0px;
    left: 10px;
    font-size: large;
    font-weight: 600;
    overflow: hidden;
}

.publish-user-info {
    float: left;
    position: relative;
    bottom: -30px;
    left: -190px;
}

.follow-button {
    float: left;
    position: relative;
    bottom: -23px;
    left: -180px;
}

.publish-user-avatar {
    float: left;
    position: relative;
    bottom: 0px;
    left: 0px;

}

.publish-date-time {
    float: right;
    position: relative;
    top: 30px;
    right: 0px;
}
</style>